//index.js
const app = getApp()
var posterHeight = 0

var posterWidth = 0
Page({
	data: {
		img_src: '',
		img_state: false,
		cap_url: '/images/cap1.png',
		capList: [{
				url: '/images/cap1.png'
			},
			{
				url: '/images/cap2.png'
			},
			{
				url: '/images/cap3.png'
			},
			{
				url: '/images/cap4.png'
			},
		],
		hatCenterX: wx.getSystemInfoSync().windowWidth / 2,
		hatCenterY: 150,
		cancelCenterX: wx.getSystemInfoSync().windowWidth / 2 - 50 - 2,
		cancelCenterY: 100,
		handleCenterX: wx.getSystemInfoSync().windowWidth / 2 + 50 - 2,
		handleCenterY: 200,
		hatSize: 100,
		scale: 1,
		rotate: 0,
		show_cap: true,
		headImg: '',
		user_id: '',
		show_login: false,

	},
	onLoad: function () {
		var that = this
		wx.showLoading({
			title: '加载中...',
		})
		setTimeout(() => {
			wx.hideLoading()
			app.createAdv()
			wx.getSystemInfo({
				success(res) {
					var is_small = ''
					var c_length = ''
					if (res.windowWidth < 330) {
						is_small = true
						c_length = 265
					} else {
						is_small = false
						c_length = 295
					}
					that.setData({
						is_small: is_small,
						c_length: c_length,
						is_show: true
					})
				}
			})
		}, 500);

	},
	onShow() {
		app.showAdv()
		var that = this
		app.wx_getWhereuserinfo().then(function (res) {
			if (res != 'new') {
				that.is_userInfo()
			} else {
				that.setData({
					show_login: true,
					is_show: true
				})
			}
		})
	},
	cantmove: function () {
		return;
	},
	is_userInfo(e) {
		var that = this
		const userInfo = wx.getStorageSync('user_info')
		this.data.user_id = userInfo.id
		if (this.data.user_id) {
			this.data.show_login = false
			if (e) {
				setTimeout(() => {
					this.sure()
				}, 500);
			}
		} else {
			this.data.show_login = true
		}
		this.setData({
			show_login: this.data.show_login
		})
		app.wx_uplogin()
	},
	onGotUserInfo: function (e) {
		var that = this
		var state = e.detail.errMsg
		if (state == 'getUserInfo:ok') {
			app.wx_loginTip()
			var that = this
			app.wx_login().then(function (result) {
				app.wx_getUserInfo().then(function (result) {
					that.is_userInfo(true)
					app.wx_loginOk()
				})
			})
		} else {
			console.log("取消授权")
		}
	},
	onReady() {
		this.hat_center_x = this.data.hatCenterX;
		this.hat_center_y = this.data.hatCenterY;
		this.cancel_center_x = this.data.cancelCenterX;
		this.cancel_center_y = this.data.cancelCenterY;
		this.handle_center_x = this.data.handleCenterX;
		this.handle_center_y = this.data.handleCenterY;
		this.scale = this.data.scale;
		this.rotate = this.data.rotate;
		this.touch_target = "";
		this.start_x = 0;
		this.start_y = 0;
	},
	touchStart(e) {
		if (e.target.id == "hat") {
			this.touch_target = "hat";
		}
		if (e.target.id == "handle") {
			this.touch_target = "handle"
		}
		if (e.target.id == "cancel") {
			this.setData({
				show_cap: false,
				cap_url: '',
				now_index: 5,
				index: 5
			})
		}
		if (e.target.id = '') {
			console.log("wuwu")
		}

		if (this.touch_target != "") {
			this.start_x = e.touches[0].clientX;
			this.start_y = e.touches[0].clientY;
		}
	},
	touchEnd(e) {
		this.hat_center_x = this.data.hatCenterX;
		this.hat_center_y = this.data.hatCenterY;
		this.cancel_center_x = this.data.cancelCenterX;
		this.cancel_center_y = this.data.cancelCenterY;
		this.handle_center_x = this.data.handleCenterX;
		this.handle_center_y = this.data.handleCenterY;
		// }
		this.touch_target = "";
		this.scale = this.data.scale;
		this.rotate = this.data.rotate;
	},
	touchMove(e) {
		var current_x = e.touches[0].clientX;
		var current_y = e.touches[0].clientY;
		var moved_x = current_x - this.start_x;
		var moved_y = current_y - this.start_y;
		if (this.touch_target == "hat") {
			this.setData({
				hatCenterX: this.data.hatCenterX + moved_x,
				hatCenterY: this.data.hatCenterY + moved_y,
				cancelCenterX: this.data.cancelCenterX + moved_x,
				cancelCenterY: this.data.cancelCenterY + moved_y,
				handleCenterX: this.data.handleCenterX + moved_x,
				handleCenterY: this.data.handleCenterY + moved_y
			})
		};
		if (this.touch_target == "handle") {
			this.setData({
				handleCenterX: this.data.handleCenterX + moved_x,
				handleCenterY: this.data.handleCenterY + moved_y,
				cancelCenterX: 2 * this.data.hatCenterX - this.data.handleCenterX,
				cancelCenterY: 2 * this.data.hatCenterY - this.data.handleCenterY
			});
			let diff_x_before = this.handle_center_x - this.hat_center_x;
			let diff_y_before = this.handle_center_y - this.hat_center_y;
			let diff_x_after = this.data.handleCenterX - this.hat_center_x;
			let diff_y_after = this.data.handleCenterY - this.hat_center_y;
			let distance_before = Math.sqrt(diff_x_before * diff_x_before + diff_y_before * diff_y_before);
			let distance_after = Math.sqrt(diff_x_after * diff_x_after + diff_y_after * diff_y_after);
			let angle_before = Math.atan2(diff_y_before, diff_x_before) / Math.PI * 180;
			let angle_after = Math.atan2(diff_y_after, diff_x_after) / Math.PI * 180;
			this.setData({
				scale: distance_after / distance_before * this.scale,
				rotate: angle_after - angle_before + this.rotate,
			})
		}
		this.start_x = current_x;
		this.start_y = current_y;
	},

	// 上传头像
	uploading: function (e) {
		var that = this
		wx.chooseImage({
			count: 1,
			sizeType: ['original', 'compressed'],
			sourceType: ['album', 'camera'],
			success(res) {
				that.data.img_src = res.tempFilePaths
				that.setData({
					img_src: that.data.img_src,
					img_state: true,
					select: true,
					now_index: 0,
					cap_url: '/images/cap1.png',
					show_canvas: false,
					show_save: false,
					// show_cap:true,
				})
			},
			fail(err) {}
		})
	},

	select(e) {
		var index = e.currentTarget.dataset.index
		var url = e.currentTarget.dataset.url
		// console.log(url)
		this.setData({
			index: index,
			cap_url: url,
			now_index: index,
			show_cap: true
		})
	},
	sure() {
		if (!this.data.img_state) {
			wx.showModal({
				title: '请先上传头像哦~',
				showCancel: false, //是否显示取消按钮
			})
		} else {
			wx.showLoading({
				title: '头像生成中...',
				mask: true,
			})
			setTimeout(() => {
				this.toDraw()
			}, 1500);
		}
	},
	toDraw() {
		var that = this
		this.setData({
			show_canvas: true,
			show_save: true,
			now_index: 5,
			index: 5,
			select: false
		})
		var scale = this.scale
		var rotate = this.rotate
		var hat_center_x = this.hat_center_x
		var hat_center_y = this.hat_center_y
		const windowWidth = wx.getSystemInfoSync().windowWidth;
		const hat_size = 100 * scale;
		var path = this.data.img_src[0]
		var ctx = wx.createCanvasContext('shareCanvas')
		var c_length = that.data.c_length
		ctx.clearRect(0, 0, windowWidth, c_length);
		wx.getImageInfo({
			src: this.data.img_src[0], //请求的网络图片路径    
			success: function (res) {
				var w = res.width
				var h = res.height
				var dw = c_length / w
				var dh = c_length / h
				if (w > c_length && h > c_length || w < c_length && h < c_length) { // 裁剪图片中间部分
					if (dw > dh) {
						ctx.drawImage(path, 0, (h - c_length / dw) / 2, w, (c_length / dw), 0, 0, c_length, c_length)
					} else {
						ctx.drawImage(path, (w - c_length / dh) / 2, 0, (c_length / dh), h, 0, 0, c_length, c_length)
					}
				} else { // 拉伸图片
					if (w < c_length) {
						ctx.drawImage(path, 0, (h - c_length / dw) / 2, w, c_length / dw, 0, 0, 300, 200)
					} else {
						ctx.drawImage(path, (w - c_length / dh) / 2, 0, c_length / dh, h, 0, 0, 300, 200)
					}
				}
				ctx.translate(hat_center_x, hat_center_y);
				ctx.rotate(rotate * Math.PI / 180);
				if (that.data.show_cap) {
					var cap_url = that.data.cap_url
					ctx.drawImage(cap_url, -hat_size / 2, -hat_size / 2, hat_size, hat_size);
				}
				ctx.draw()
				wx.hideLoading()
				wx.showToast({
					title: '图片生成成功',
					icon: 'success',
					duration: 1500,
				})
			},
			fail: function (res) {}
		})

	},
	save() {
		var that = this
		var token = wx.getStorageSync('token')
		wx.canvasToTempFilePath({
			x: 0,
			y: 0,
			canvasId: 'shareCanvas',
			success: function (res) {
				let headImg = res.tempFilePath;
				wx.authorize({
					scope: 'scope.writePhotosAlbum',
					success(e) {
						wx.hideLoading()
						wx.saveImageToPhotosAlbum({
							filePath: headImg,
							success(res) {
								wx.showToast({
									title: '已保存至相册',
									duration: 1500,
									mask: true,
								})
								// that.setData({
								// 	img_src:'',
								// 	index:5,
								// 	show_cap:false,
								// 	img_state:false,
								// 	show_canvas:false,
								// 	show_save:false,
								// })
							},
						})
					},
					fail(err) {
						wx.showModal({
							title: '提示',
							content: '需要您授权保存相册',
							confirmText: '授权',
							success(res) {
								if (res.confirm) {
									wx.openSetting({
										success(settingdata) {
											if (settingdata.authSetting['scope.writePhotosAlbum']) {
												wx.showToast({
													title: '获取权限成功',
													duration: 1500,
												})
											} else {
												wx.showModal({
													title: '提示',
													content: '获取权限失败，将无法保存到相册哦~',
													showCancel: false,
												})
											}
										},
										fail(failData) {},
										complete(finishData) {}
									})
								}
							}
						})
					},
				})
			},
		})
	},
})